package com.lkd.http.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.*;
import com.lkd.exception.LogicException;
import com.lkd.feign.VMService;
import com.lkd.http.vo.*;
import com.lkd.service.*;
import com.lkd.vo.Pager;
import lombok.Data;
import com.lkd.vo.UserWorkVO;
import lombok.SneakyThrows;

import java.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;


import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/task")
public class TaskController extends  BaseController{
    @Autowired
    private TaskService taskService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private TaskTypeService taskTypeService;



    /**
     * 搜索工单
     * @param pageIndex
     * @param pageSize
     * @param innerCode 设备编号
     * @param userId  工单所属人Id
     * @param taskCode 工单编号
     * @param status 工单状态
     * @param isRepair 是否是维修工单
     * @return
     */
    @GetMapping("/search")
    public Pager<TaskEntity> search(
            @RequestParam(value = "pageIndex",required = false,defaultValue = "1") Long pageIndex,
            @RequestParam(value = "pageSize",required = false,defaultValue = "10") Long pageSize,
            @RequestParam(value = "innerCode",required = false,defaultValue = "") String innerCode,
            @RequestParam(value = "userId",required = false,defaultValue = "") Integer userId,
            @RequestParam(value = "taskCode",required = false,defaultValue = "") String taskCode,
            @RequestParam(value = "status",required = false,defaultValue = "") Integer status,
            @RequestParam(value = "isRepair",required = false,defaultValue = "") Boolean isRepair,
            @RequestParam(value = "start",required = false,defaultValue = "") String start,
            @RequestParam(value = "end",required = false,defaultValue = "") String end){
        return taskService.search(pageIndex,pageSize,innerCode,userId,taskCode,status,isRepair,start,end);
    }



    /**
     * 根据taskId查询
     * @param taskId
     * @return 实体
     */
    @GetMapping("/taskInfo/{taskId}")
    public TaskEntity findById(@PathVariable Long taskId){
        return taskService.getById(taskId);
    }


    @GetMapping("/allTaskStatus")
    public List<TaskStatusTypeEntity> getAllStatus(){
        return taskService.getAllStatus();
    }

    /**
     * 获取工单类型
     * @return
     */
    @GetMapping("/typeList")
    public List<TaskTypeEntity> getProductionTypeList(){
        return taskTypeService.list();
    }

    /**
     * 获取工单详情
     * @param taskId
     * @return
     */
    @GetMapping("/details/{taskId}")
    public List<TaskDetailsEntity> getDetail(@PathVariable long taskId) {
        return taskDetailsService.getByTaskId(taskId);
    }

    @PostMapping("/create")
    public boolean create(@RequestBody TaskViewModel taskViewModel) {
        //获取用户ID,设置到参数对象中
        taskViewModel.setAssignorId(getUserId());
        return taskService.create(taskViewModel);
    }

    /**
     * 接受工单
     * @param id
     * @return
     */
    @GetMapping("/accept/{taskId}")
    public boolean accept(@PathVariable("taskId") Long id) {
        //判断工单执行人是否为当前登录用户
        TaskEntity task = taskService.getById(id);
        if (!Objects.equals(task.getUserId(), getUserId())) {
            throw new LogicException("操作非法");
        }
        return taskService.accept(task);
    }

    /**
     * 取消工单
     * @param taskId
     * @param cancelVm
     * @return
     */
    @PostMapping("/cancel/{taskId}")
    public boolean cancel(@PathVariable("taskId") String taskId,
                          @RequestBody CancelTaskViewModel cancelVm) {
        Long id = Long.valueOf(taskId);
        //判断工单执行人是否为当前登录用户 判断工单指派人是否未当前登录用户
        TaskEntity task = taskService.getById(id);
        if (task.getCreateType().equals(VMSystem.VM_CREATE_TYPE_MANUL) &&
                !(task.getUserId().intValue() == getUserId().intValue()
                        || task.getAssignorId().intValue() == getUserId().intValue())) {
            throw new LogicException("操作非法");
        }
        //如果是自动工单，判断当前用户是否是管理员，获取当前用户roleCode 1001
        return taskService.cancelTask(id, cancelVm);
    }

    /**
     * 完成工单
     * @param taskId
     * @return
     */
    @GetMapping("/complete/{taskId}")
    public boolean complete(@PathVariable("taskId") String taskId) {
        Long id = Long.valueOf(taskId);
        //判断工单执行人是否为当前登录用户
        TaskEntity task = taskService.getById(id);
        if (task.getUserId().intValue() != getUserId().intValue()) {
            throw new LogicException("操作非法");
        }
        return taskService.completeTask(id);
    }

    /**
     * 人效排名月度统计
     * @param start
     * @param end
     * @param isRepair
     * @param regionId
     * @return
     */
    @GetMapping("/userWorkTop10/{start}/{end}/{isRepair}/{regionId}")
    public List<UserWorkVO> personnelRankings (@PathVariable("start") String start,
                                         @PathVariable("end") String end,
                                         @PathVariable("isRepair") Boolean isRepair,
                                         @PathVariable("regionId") Long regionId){


        return taskService.getRank(start,end,isRepair,regionId);
    }

    @Autowired
    private MqttProducer mqttProducer;

    @GetMapping("/msg")
    public void msg() throws JsonProcessingException {
        TaskCompleteContract contract = new TaskCompleteContract();
        contract.setInnerCode("123");
        mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC,1,contract);
    }

    /**
     * 获取当时工单汇总信息(人员统计头部信息)
     *
     * @param start
     * @param end
     * @return
     */
    @GetMapping("/taskReportInfo/{start}/{end}")
    public List<TaskReportInfoVO> taskReportInfo(@PathVariable("start") String start, @PathVariable("end") String end) {

        return taskService.taskReportInfo(start, end);

    }

    /**
     * 工单状态统计
     *
     * @param start
     * @param end
     * @return
     */
    @GetMapping("/collectReport/{start}/{end}")
    public List<TaskCollectEntity> collect(@PathVariable("start") String start, @PathVariable("end") String end) {
        if (start == null || end == null) {
            throw new LogicException("参数传递有误!");
        }
        return taskService.getCollectReport(start, end);
    }
}